const Koa = require("koa");
const app = new Koa();

const KoaRouter = require("koa-router");
const router = new KoaRouter();

const bodyparser = require("koa-bodyparser");

const mysql = require("mysql");

app.use(bodyparser());

router.post("/register", async (ctx) => {
    const { username, password, nickname } = ctx.request.body;
    // 用户名必须要唯一
    let res = await query("select * from user where username = ?", [username]);
    if (res.length > 0) {
        ctx.body = {
            code: 403,
            message: "用户已注册",
        };
        return;
    }
    res = await query(
        "insert into user (username, password, nickname) values (?, ?, ?)",
        [username, passwordEncoder(password), nickname]
    );
    if (res.affectedRows !== 1) {
        ctx.body = {
            code: 500,
            message: "注册失败",
        };
        return;
    }
    ctx.body = {
        code: 201,
        message: "注册成功",
    };
});

router.post("/login", async (ctx) => {
    const { username, password } = ctx.request.body;
    let res = await query("select * from user where username = ?", [username]);
    if (res.length === 0) {
        ctx.body = {
            code: 404,
            message: "用户不存在",
        };
        return;
    }
    const user = res[0];
    // 判断密码是否正确
    if (user.password !== passwordEncoder(password)) {
        ctx.body = {
            code: 400,
            message: "用户密码不匹配",
        };
        return;
    }
    delete user.password;
    // 登录成功
    ctx.body = {
        code: 200,
        data: {
            user,
        },
        message: "登录成功",
    };
});

app.use(router.routes());

app.listen(9100, () => {
    console.log("Koa server running at http://localhost:9100");
});

/**
 * 发送 SQL 语句到 MySQL 服务器，并执行该 SQL 语句，返回结果
 * @param {string} sql 要发送 SQL 语句
 * @param {array} params SQL 语句中包含的参数
 */
function query(sql, params = []) {
    // 创建链接配置
    const con = mysql.createConnection({
        host: "localhost",
        port: 3306,
        user: "root",
        password: "root",
        database: "api-koa",
    });

    // 发送 SQL 语句
    return new Promise((resolve, reject) => {
        // 发送 http 请求
        con.query(sql, params, (error, data) => {
            if (error) {
                reject(error);
            } else {
                resolve(data);
            }
            // 关闭
            con.end();
        });
    });
}
const crypto = require("crypto");
function passwordEncoder(raw_password) {
    return crypto
        .createHmac("sha256", "2h3ih21u3i21")
        .update(raw_password)
        .digest("hex");
}
